package com.wiseasy.ecrutils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class UsbHandler extends Handler {
    private UsbListener listener;
    private Context context;

    public UsbHandler(Context context, UsbListener listener) {
        this.context = context;
        this.listener = listener;
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case Flags.SHOW_TOAST:
                showToast(msg.obj.toString());
                break;
            case Flags.SERIAL_PORT_SUCCESS:
                startSerialPortReading();
                break;
            case Flags.HSM_MANAGE_RECEIVE:
            default:
                handleHSMMessage(msg.obj.toString());
                break;
        }
    }


    private void showToast(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    private void startSerialPortReading() {
        SerialPortUtils.getInstance().waitPortData = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (SerialPortUtils.getInstance().waitPortData) {
                    SerialPortUtils.getInstance().readDataBySerialPort(UsbHandler.this);
                    SystemClock.sleep(300);
                }
            }
        }).start();
    }


    private void handleHSMMessage(String message) {
//        Log.e(TAG, "THIS IS THE MESSAGE: $message")
        if (listener != null) {
            listener.onGetData(message);
        }
    }

    public interface UsbListener {
        void onGetData(String data);
    }
}
